package com.easylinkin.linkappapi.meterbilling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.meterbilling.entity.BaseBilling;
import com.easylinkin.linkappapi.meterbilling.entity.BaseBillingHistory;
import com.easylinkin.linkappapi.meterbilling.entity.ext.BaseBillingExt;
import com.easylinkin.linkappapi.meterbilling.mapper.BaseMeterBillingHistoryMapper;
import com.easylinkin.linkappapi.meterbilling.mapper.BaseMeterBillingMapper;
import com.easylinkin.linkappapi.meterbilling.mapper.RoomBillingRefMapper;
import com.easylinkin.linkappapi.meterbilling.service.BillingStandardService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * class info :计费标准service实现类
 *
 * @author liuqihang
 * @date 2021/7/12 16:12
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BillingStandardServiceImpl extends ServiceImpl<BaseMeterBillingMapper, BaseBilling> implements BillingStandardService {

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Resource
    private RoomBillingRefMapper roomBillingRefMapper;

    @Resource
    private BaseMeterBillingHistoryMapper baseMeterBillingHistoryMapper;

    @Resource
    private CommonService commonService;

    @Override
    public String saveBillingStandardData(BaseBilling baseBilling) {
        Assert.notNull(baseBilling.getMeterType(), "设备类型不能为空");
        Assert.notNull(baseBilling.getPriceName(), "计费标准名称不能为空");
        Assert.notNull(baseBilling.getPrice(), "价格不能为空");

        //验证是否重复
        if(checkPriceName(baseBilling)){
            return "计费名称重复";
        }
        LinkappUser current = linkappUserContextProducer.getCurrent();
        if(current == null){
            throw new IllegalArgumentException("请登录...");
        }
        baseBilling.setTenantId(current.getTenantId());
        commonService.setCreateAndModifyInfo(baseBilling);
        baseMapper.insert(baseBilling);

        //备份至计费标准历史表中
        BaseBillingHistory  baseBillingHistory = new BaseBillingHistory();
        BeanUtils.copyProperties(baseBilling, baseBillingHistory);
        baseBillingHistory.setVersion(1);
        baseBillingHistory.setBillingId(baseBilling.getId());
        baseMeterBillingHistoryMapper.insert(baseBillingHistory);
        return null;
    }

    /**
     * 验证计费标准名称是否重复
     * @param baseBilling
     * @return true:重复，false:有效
     */
    private boolean checkPriceName(BaseBilling baseBilling){
        QueryWrapper qw = new QueryWrapper();
        qw.eq("delete_status", 0);
        qw.eq("is_valid", 0);
        qw.eq("price_name", baseBilling.getPriceName());
        if(baseBilling.getId() != null){
            qw.notIn("id", baseBilling.getId());
        }
        List list = baseMapper.selectList(qw);
        if(list == null || list.size() <= 0){
            return false;
        }
        return true;
    }

    @Override
    public BaseBilling getBillingStandardInfoById(Integer id){
        BaseBilling baseBilling = baseMapper.selectById(id);
        return baseBilling;
    }

    @Override
    public List<BaseBillingHistory> getBaseBillingHistoryInfoById(Integer baseBillingId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("billing_id", baseBillingId);
        qw.orderByDesc("version");
        List<BaseBillingHistory> list = baseMeterBillingHistoryMapper.selectList(qw);
        return list;
    }

    @Override
    public BaseBillingHistory getNewBaseBillingInfoById(Integer baseBillingId) {
        List<BaseBillingHistory> baseBillingHistoryInfoById = getBaseBillingHistoryInfoById(baseBillingId);
        return baseBillingHistoryInfoById.get(0);
    }

    @Override
    public String updateBillingStandardData(BaseBilling baseBilling) {
        Assert.notNull(baseBilling.getId(), "计费标准ID不能为空");
        Assert.notNull(baseBilling.getMeterType(), "设备类型不能为空");
        Assert.notNull(baseBilling.getPriceName(), "计费标准名称不能为空");
        Assert.notNull(baseBilling.getPrice(), "价格不能为空");

        //验证是否重复
        if(checkPriceName(baseBilling)){
            return "计费名称重复";
        }

        BaseBillingHistory  baseBillingHistory = new BaseBillingHistory();
        BeanUtils.copyProperties(baseBilling, baseBillingHistory);

        List<BaseBillingHistory> baseBillingHistoryInfoById = getBaseBillingHistoryInfoById(baseBilling.getId());
        if(baseBillingHistoryInfoById == null || baseBillingHistoryInfoById.isEmpty()){
            baseBillingHistory.setVersion(1);
        }else {
            Integer version = baseBillingHistoryInfoById.get(0).getVersion();
            baseBillingHistory.setVersion(version + 1);
        }

        baseBillingHistory.setBillingId(baseBilling.getId());
        commonService.setCreateAndModifyInfo(baseBillingHistory);
        LinkappUser current = linkappUserContextProducer.getCurrent();
        if(current == null){
            throw new IllegalArgumentException("请登录...");
        }
        baseBillingHistory.setTenantId(current.getTenantId());
        baseMeterBillingHistoryMapper.insert(baseBillingHistory);

        commonService.setModifyInfo(baseBilling);
        baseMapper.updateById(baseBilling);
        return null;
    }

    @Override
    public String deleteBillingStandardData(BaseBilling baseBilling) {
        Assert.notNull(baseBilling.getId(), "计费标准ID不能为空");

        //验证计费标准是否在使用
        QueryWrapper qw = new QueryWrapper();
        qw.eq("billing_id", baseBilling.getId());
        Integer count = roomBillingRefMapper.selectCount(qw);
        if(count != null && count > 0){
            return "该计费标准使用中";
        }

        baseBilling.setDeleteStatus(1);
        baseMapper.updateById(baseBilling);
        return null;
    }

    @Override
    public IPage<BaseBillingExt> getBaseBillingList(Page page, BaseBilling baseBilling) {
        LinkappUser current = linkappUserContextProducer.getCurrent();
        if(current == null){
            throw new IllegalArgumentException("请登录...");
        }
        baseBilling.setTenantId(current.getTenantId());
        return baseMapper.getBaseBillingList(page, baseBilling);
    }

    @Override
    public List<BaseBillingExt> getBaseBillingByMeterType(BaseBilling baseBilling) {
        LinkappUser current = linkappUserContextProducer.getCurrent();
        if(current == null){
            throw new IllegalArgumentException("请登录...");
        }
        baseBilling.setTenantId(current.getTenantId());
        return baseMapper.getBaseBillingList(baseBilling);
    }
}
